<?php
$sanitize_all_escapes = true;

$fake_register_globals = false;

require_once("../../globals.php");
require_once("$srcdir/patient.inc");
require_once("$srcdir/acl.inc");
require_once("$srcdir/classes/Address.class.php");
require_once("$srcdir/classes/InsuranceCompany.class.php");
require_once("$srcdir/classes/Document.class.php");
require_once("$srcdir/options.inc.php");
require_once("../history/history.inc.php");
require_once("$srcdir/formatting.inc.php");
require_once("$srcdir/edi.inc");
require_once("$srcdir/clinical_rules.php");
include_once("$srcdir/lists.inc");
include_once("$srcdir/formdata.inc.php");
require_once("$srcdir/patient_provider.inc.php");


if (!acl_check('mdls', 'bsqdrpd'))
    die('Acceso no autorizado.');

if (isset($_GET['set_pid'])) {
    include_once("$srcdir/pid.inc");
    setpid($_GET['set_pid']);
    session_start();
    $_SESSION['pid'] = $_GET['set_pid'];

    $querySex = $query = " SELECT sex 
                    FROM `patient_data` WHERE patient_data.id = " . $_SESSION['pid'];
    $resultSex = sqlStatement($querySex);

    $sex = sqlFetchArray($resultSex);

    $_SESSION['sex'] = $sex['sex'];
   
    //if()
}

/*echo "<pre>";
print_r($_SESSION);
echo "</pre>";*/

$query = " SELECT * 
                    FROM `form_encounter` inner join patient_data on ( form_encounter.pid = patient_data.pid )
                    WHERE form_encounter.provider_id = " . $_SESSION['authUserID'] . " AND form_encounter.closed = 0 ";
$result = sqlStatement($query);
$row = sqlFetchArray($result);
$the_pid = $row['pid'];
$the_encounter = $row['encounter'];
                           
/*
  echo "<pre>";
  print_r($_SESSION);
  echo "</pre>";
 */
$active_reminders = false;
if ((!isset($_SESSION['alert_notify_pid']) || ($_SESSION['alert_notify_pid'] != $pid)) && isset($_GET['set_pid']) && acl_check('patients', 'med') && $GLOBALS['enable_cdr'] && $GLOBALS['enable_cdr_crp']) {
    // showing a new patient, so check for active reminders
    $active_reminders = active_alert_summary($pid, "reminders-due");
}

function pic_array() {
    $imagedir = $GLOBALS['OE_SITE_DIR'] . "/documents/$pid/demographics";
    $imagepath = "$web_root/sites/" . $_SESSION['site_id'] . "/documents/$pid/demographics";

    $picture_directory = "Patient Photograph"; //change this if you want
    $pics = array();
    $sql_query = "select documents.id from documents join categories_to_documents on documents.id = categories_to_documents.document_id join categories on categories.id = categories_to_documents.category_id where categories.name like ? and documents.foreign_id = ?";
    if ($query = sqlStatement($sql_query, array($picture_directory, $_SESSION['pid']))) {
        $results = sqlFetchArray($query);

        if (count($results) > 0) {
            /* echo "<pre>";
              print_r($results);
              echo "</pre>";die;
              <img src='$imagepath/photo.jpg' />
             */

            $tmp = $results['id'];
            if (isset($tmp)) {
                array_push($pics, "<div id='photograph' class='patient_pic'><img width='100px' height='100px' src='" . $GLOBALS['webroot'] . "/controller.php?document&retrieve&patient_id=" . htmlspecialchars($_SESSION['pid'], ENT_QUOTES) . "&document_id=" . htmlspecialchars($tmp, ENT_QUOTES) . "&as_file=false' alt='Foto'></div>\n");
            } else {
                /* array_push($pics, "<div id='photograph' class='patient_pic'><a href='' onclick=\"return sendimage(" . $_SESSION['pid'] . ", 'photo');\" " . "title='Click para agregar la foto del paciente'><img width='100px' src='" . $GLOBALS['webroot'] . "/images/patient.png' alt='Foto'></a></div>\n"); */

                array_push($pics, "<div id='photograph' class='patient_pic'><img width='100px' src='" . $GLOBALS['webroot'] . "/images/patient.png' alt='Foto'></div>\n");

                //---Huella digital
                /*
                  $imagedir  = $GLOBALS['OE_SITE_DIR'] . "/documents/$pid/demographics";
                  $imagepath = "$web_root/sites/" . $_SESSION['site_id'] . "/documents/$pid/demographics";
                  echo "   <a href='' onclick=\"return sendimage($pid, 'fingerprint');\" " .
                  "title='Click to attach fingerprint'>\n";
                  if (is_file("$imagedir/fingerprint.jpg")) {
                  echo "   <img src='$imagepath/fingerprint.jpg' /></a>\n";
                  } else {
                  echo "   Attach Biometric Fingerprint</a><br />\n";
                  }
                  echo "   <br />&nbsp;<br />\n"; */
            }
        } else {
            array_push($pics, "<div id='photograph' class='patient_pic'><img height='88px' src='../../../images/patient.png' alt='Foto'></div>\n");
        }
    }
    return $pics;
}

function get_document_by_catg($pid, $doc_catg) {

    $result = array();

    if ($pid and $doc_catg) {
        $result = sqlQuery("SELECT d.id, d.date, d.url FROM " .
                "documents AS d, categories_to_documents AS cd, categories AS c " .
                "WHERE d.foreign_id = ? " .
                "AND cd.document_id = d.id " .
                "AND c.id = cd.category_id " .
                "AND c.name LIKE ? " .
                "ORDER BY d.date DESC LIMIT 1", array($pid, $doc_catg));
    }

    return($result['id']);
}

function check_open_encounter() {
    $query = " SELECT * " .
            " FROM form_encounter " .
            " WHERE closed = 0 AND provider_id = " . $_SESSION['authUserID'];
    $result = sqlStatement($query);
    if (sqlNumRows($result) > 0) {
        return true;
    } else {
        return false;
    }
}

function close_open_encounters() {
//    global $the_pid;
    $query = " UPDATE form_encounter SET closed = 1 WHERE provider_id = " . $_SESSION['authUserID'];
    sqlStatement($query);
}

function image_widget($doc_id, $doc_catg) {
    global $pid, $web_root;
    $docobj = new Document($doc_id);
    $image_file = $docobj->get_url_file();
    $extension = substr($image_file, strrpos($image_file, "."));
    $viewable_types = array('.png', '.jpg', '.jpeg', '.png', '.bmp', '.PNG', '.JPG', '.JPEG', '.PNG', '.BMP'); // image ext supported by fancybox viewer
    if (in_array($extension, $viewable_types)) { // extention matches list
        $to_url = "<td> <a href = $web_root" .
                "/controller.php?document&retrieve&patient_id=$pid&document_id=$doc_id" .
                "/tmp$extension" . // Force image type URL for fancybox
                " onclick=top.restoreSession(); class='image_modal'>" .
                " <img src = $web_root" .
                "/controller.php?document&retrieve&patient_id=$pid&document_id=$doc_id" .
                " width=100 alt='$doc_catg:$image_file'>  </a> </td> <td valign='center'>" .
                htmlspecialchars($doc_catg) . '<br />&nbsp;' . htmlspecialchars($image_file) .
                "</td>";
    } else {
        $to_url = "<td> <a href='" . $web_root . "/controller.php?document&retrieve" .
                "&patient_id=$pid&document_id=$doc_id'" .
                " onclick='top.restoreSession()' class='css_button_small'>" .
                "<span>" .
                htmlspecialchars(xl("View"), ENT_QUOTES) . "</a> &nbsp;" .
                htmlspecialchars("$doc_catg - $image_file", ENT_QUOTES) .
                "</span> </td>";
    }
    echo "<table><tr>";
    echo $to_url;
    echo "</tr></table>";
}

if ($_REQUEST['closed_old'] == 1) {
    close_open_encounters();
}

// Determine if the Vitals form is in use for this site.
$tmp = sqlQuery("SELECT count(*) AS count FROM registry WHERE " .
        "directory = 'vitals' AND state = 1");
$vitals_is_registered = $tmp['count'];

$result = getPatientData($pid, "*, DATE_FORMAT(DOB,'%Y-%m-%d') as DOB_YMD");

/* echo "<pre>";
  print_r($result);
  echo "</pre>"; */

$result2 = getEmployerData($pid);
$result3 = getInsuranceData($pid, "primary", "copay, provider, DATE_FORMAT(`date`,'%Y-%m-%d') as effdate");
$insco_name = "";
if ($result3['provider']) {   // Use provider in case there is an ins record w/ unassigned insco
    $insco_name = getInsuranceProvider($result3['provider']);
}
?>
<html>

    <head>
        <link rel="stylesheet" href="<?php echo $web_root; ?>/library/js/redmond/jquery-ui-1.10.3.custom.min.css" type="text/css"/>
        <link rel="stylesheet" type="text/css" href="<?php echo $GLOBALS['webroot'] ?>/interface/themes/jquery.fancybox.css?v=2.1.5" media="screen"/>
        <link rel="stylesheet" type="text/css" href="<?php echo $GLOBALS['webroot'] ?>/interface/themes/jquery-accordion.css" >
        <link rel="stylesheet" href="<?php echo $web_root; ?>/patients/css/appointments.css" type="text/css"/>

        <script type="text/javascript" src="<?php echo $GLOBALS['webroot'] ?>/library/js/common.js"></script>
        <script type="text/javascript" src="<?php echo $GLOBALS['webroot'] ?>/library/dialog.js"></script>
        <script type="text/javascript" src="<?php echo $GLOBALS['webroot'] ?>/library/js/jquery.fancybox.pack.js"></script>
        <script type="text/javascript" src="<?php echo $GLOBALS['webroot'] ?>/library/js/jquery-accordion.js"></script>
        <script type="text/javascript" language="JavaScript">
            var mypcc = '<?php echo htmlspecialchars($GLOBALS['phone_country_code'], ENT_QUOTES); ?>';

            function oldEvt(eventid) {
                dlgopen('../../main/calendar/add_edit_event.php?eid=' + eventid, '_blank', 550, 350);
            }

            function advdirconfigure() {
                dlgopen('advancedirectives.php', '_blank', 500, 450);
            }

            function refreshme() {
                top.restoreSession();
            }

            // Process click on Delete link.
            function deleteme() {
                dlgopen('../deleter.php?patient=<?php echo htmlspecialchars($pid, ENT_QUOTES); ?>', '_blank', 500, 450);
                return false;
            }

            // Called by the deleteme.php window on a successful delete.
            function imdeleted() {
<?php if ($GLOBALS['concurrent_layout']) { ?>
                    //                    parent.left_nav.clearPatient();
<?php } else { ?>
                    top.restoreSession();
                    top.location.href = '../main/main_screen.php';
<?php } ?>
            }

            function validate() {
                var f = document.forms[0];
<?php
if ($GLOBALS['athletic_team']) {
    echo "  if (f.form_userdate1.value != f.form_original_userdate1.value) {\n";
    $irow = sqlQuery("SELECT id, title FROM lists WHERE " .
            "pid = ? AND enddate IS NULL ORDER BY begdate DESC LIMIT 1", array($pid));
    if (!empty($irow)) {
        ?>
                        if (confirm('Do you wish to also set this new return date in the issue titled "<?php echo htmlspecialchars($irow['title'], ENT_QUOTES); ?>"?')) {
                            f.form_issue_id.value = '<?php echo htmlspecialchars($irow['id'], ENT_QUOTES); ?>';
                        } else {
                            alert('OK, you will need to manually update the return date in any affected issue(s).');
                        }
    <?php } else { ?>
                        alert('You have changed the return date but there are no open issues. You probably need to create or modify one.');
        <?php
    } // end empty $irow
    echo "  }\n";
} // end athletic team
?>
                return true;
            }

            function newEvt() {
                dlgopen('appointments', '../main/calendar/add_edit_event.php?patientid=<?php echo htmlspecialchars($pid, ENT_QUOTES); ?>&src=1', '_blank', 700, 380);
                return false;
            }

            // JavaScript stuff to do when a new patient is set.
            function setMyPatient() {
<?php if (isset($_GET['set_pid'])) { ?>

                    setPatient(<?php
    echo "'" . htmlspecialchars(($result['fname']) . " " . ($result['lname']), ENT_QUOTES) .
    "'," . htmlspecialchars($pid, ENT_QUOTES) . ",'" . htmlspecialchars(($result['pubpid']), ENT_QUOTES) .
    "'";
    ?>);

                    var EncounterDateArray = new Array;
                    var CalendarCategoryArray = new Array;
                    var EncounterIdArray = new Array;
                    var Count = 0;

    <?php
    //Encounter details are stored to javacript as array.
    $result4 = sqlStatement("SELECT fe.encounter,fe.date,openemr_postcalendar_categories.pc_catname FROM form_encounter AS fe " .
            " left join openemr_postcalendar_categories on fe.pc_catid=openemr_postcalendar_categories.pc_catid  WHERE fe.pid = ? order by fe.date desc", array($pid));
    if (sqlNumRows($result4) > 0) {
        while ($rowresult4 = sqlFetchArray($result4)) {
            ?>
                            EncounterIdArray[Count] = '<?php echo htmlspecialchars($rowresult4['encounter'], ENT_QUOTES); ?>';
                            EncounterDateArray[Count] = '<?php echo htmlspecialchars(oeFormatShortDate(date("Y-m-d", strtotime($rowresult4['date']))), ENT_QUOTES); ?>';
                            CalendarCategoryArray[Count] = '<?php echo htmlspecialchars(xl_appt_category($rowresult4['pc_catname']), ENT_QUOTES); ?>';
                            Count++;
            <?php
        }
    }
    ?>
                    setPatientEncounter(EncounterIdArray, EncounterDateArray, CalendarCategoryArray);
<?php } // end setting new pid                      ?>
            }

            var nombre, pacienteId, identificacion;

            function setPatient(pname, pid, pubpid) {
                nombre = pname;
                pacienteId = pid;
                identificacion = pubpid;
                var str = '<a href=\'javascript:;\' onclick="loadPatient(' + pid + '); return false;" title="PID = ' + pid + '"><b>' + pname + ' (' + pubpid + ')</b></a>';
                $("#current_patient").html(str);
                if (pid == active_pid)
                    return;
                $("#current_encounter").html('<b><?php xl('None', 'e'); ?></b>');
                active_pid = pid;
                active_encounter = 0;
                //if (frname) reloadPatient(frname);
                $('#current_patient_block').show();
                var encounter_block = $('#current_encounter_block');
                $(encounter_block).hide();
            }

            function setPatientEncounter(EncounterIdArray, EncounterDateArray, CalendarCategoryArray) {
                //This function lists all encounters of the patient.
                //This function writes the drop down in the top frame.
                //It is called when a new patient is create/selected from the search menu.
                var str = '<Select id="EncounterHistory" onchange="{toencounter(this.options[this.selectedIndex].value)}">';
                str += '<option value=""><?php echo htmlspecialchars(xl('Encounter History'), ENT_QUOTES) ?></option>';
                <?php if (!acl_check('admin', 'adm_cnf') ){?>
                    str+='<option value="New Encounter"><?php echo htmlspecialchars( xl('New Encounter'), ENT_QUOTES) ?></option>';
                <?php }?>
                str += '<option value="Past Encounter List"><?php echo htmlspecialchars(xl('Past Encounter List'), ENT_QUOTES) ?></option>';
                for (CountEncounter = 0; CountEncounter < EncounterDateArray.length; CountEncounter++)
                {
                    str += '<option value="' + EncounterIdArray[CountEncounter] + '~' + EncounterDateArray[CountEncounter] + '">' + EncounterDateArray[CountEncounter] + '-' + CalendarCategoryArray[CountEncounter] + '</option>';
                }
                str += '</Select>';
                $('#past_encounter_block').show();
                $("#past_encounter").html(str);
            }

            function check_current_encounter() {
                var response = '';
                $.ajax({
                    type: "POST",
                    cache: false,
                    url: '../patient_file/summary/current_encounter.php?type=1',
                    data: '', // all form fields
                    success: function(data) {
                        $("#enc_val").val(data);
                        //alert($("#enc_val").val());
                    } // success
                }); // ajax
                //return response;

            }

            function goPid(pid) {

                $.ajax({
                    type: "POST",
                    cache: false,
                    url: '../patient_file/summary/demographics.php?set_pid=' + pid,
                    data: '', // all form fields
                    success: function(data) {
                        $("#info").html(data);
                    } // success
                }); // ajax
            }

            /*Signos vitales*/
            function refreshSignos() {
                $("#signos").load("<?php echo $web_root; ?>/patients/get_vitals_fragment.php?medico=1&set_pid=<?php echo $_REQUEST['set_pid']; ?>");
            }

            /*Citas*/
            function refreshCitas() {
                $("#citas").load("<?php echo $web_root; ?>/patients/get_appointments.php?medico=1&set_pid=<?php echo $_REQUEST['set_pid']; ?>");
            }

            /*Tratamientos*/
            function refreshMedications() {
                $("#medicamentos").load("<?php echo $web_root; ?>/patients/get_medications.php?medico=1&set_pid=<?php echo $_REQUEST['set_pid']; ?>");
            }

            function refreshPrescriptions() {
                $("#patient_stats_prescriptions").load("<?php echo $web_root; ?>/patients/get_prescriptions.php?medico=1&set_pid=<?php echo $_REQUEST['set_pid']; ?>");
            }

            /*Alergias*/
            function refreshAllergies() {
                $("#alergias").load("<?php echo $web_root; ?>/patients/get_allergies.php?medico=1&set_pid=<?php echo $_REQUEST['set_pid']; ?>");
            }

            /*Inmunizaciones*/
            function refreshVacunas() {
                $("#vacunaciones").load("<?php echo $web_root; ?>/patients/get_immunizations.php?medico=1&set_pid=<?php echo $_REQUEST['set_pid']; ?>");
            }



            /*Diagnosticos Medicos*/
            function refreshProblemasMedicos() {
                $("#problemasMedicos").load("<?php echo $web_root; ?>/patients/get_issues.php?medico=1&set_pid=<?php echo $_REQUEST['set_pid']; ?>");
            }

            /* Dropdown de consultas medicas */
            function toencounter(rawdata) {
                var url = '';
                document.getElementById('EncounterHistory').selectedIndex = 0;
                if (rawdata === '')
                {
                    return false;
                }
                else if (rawdata === 'New Encounter')
                {
                    url = '../forms/newpatient/new.php?autoloaded=1&amp;calenc=';
                    parent.$.fancybox({
                        href: url,
                        maxWidth: 700,
                        minHeight: 400,
                        fitToView: false,
                        type: 'iframe',
                        iframe: {
                               preload: false // fixes issue with iframe and IE
                        },
                        helpers: {
                            overlay: {
                                opacity: 0.3,
                                css: {
                                    'background': 'rgba(255, 254, 254,0.85)'
                                }
                            } // overlay
                        }, // helpers
                        beforeShow: function() {
                            /*this.width = $('.fancybox-iframe').contents().find('html').width();
                             this.height = $('.fancybox-iframe').contents().find('html').height();*/
                        },
                    }); // fancybox
                    return true;
                }
                else if (rawdata === 'Past Encounter List')
                {
                    $("#column_left").load("../patient_file/summary/get_encounters.php");
                    return true;
                }

                var parts = rawdata.split("~");
                var enc = parts[0];
                var datestr = parts[1];

                url = '../patient_file/encounter/forms.php?set_encounter=' + enc;

                //alert(url);
                $("#column_left").load(url);
            }


            $(document).ready(function() {
                setMyPatient();
                refreshCitas();
                //nos();
                refreshMedications();
                refreshAllergies();
                refreshProblemasMedicos();
                refreshPrescriptions();

                //timeline
                $("#column_left").load("../patient_file/summary/get_encounters.php");

                //Notas
                $("#pnotes_ps_expand").load("../patient_file/summary/pnotes_fragment.php");

                //Publicaciones
                $("#disclosures_ps_expand").load("../patient_file/summary/disc_fragment.php");

<?php if ($GLOBALS['enable_cdr'] && $GLOBALS['enable_cdr_crw']) { ?>
                    $("#clinical_reminders_ps_expand").load("../patient_file/summary/clinical_reminders_fragment.php", function() {
                        $('.iframe_reminders').click(function(e) {
                            e.preventDefault();
                            parent.$.fancybox({
                                href: this.href,
                                autoSize: true,
                                type: 'iframe',
                                iframe: {
                                    preload: false // fixes issue with iframe and IE
                                },
                                helpers: {
                                    overlay: {
                                        opacity: 0.3,
                                        css: {
                                            'background': 'rgba(255, 254, 254,0.85)'
                                        }
                                    } // overlay
                                } // helpers
                            }); // fancybox
                        }); // click 	
                    });
<?php } // end crw                     ?>

                //Recordatorios del paciente
<?php if ($GLOBALS['enable_cdr'] && $GLOBALS['enable_cdr_prw']) { ?>
                    $("#patient_reminders_ps_expand").load("../patient_file/summary/patient_reminders_fragment.php");
<?php } // end prw                     ?>

                //Constantes vitales
<?php if ($vitals_is_registered && acl_check('patients', 'med')) { ?>
                    $("#vitals_ps_expand").load("../patient_file/summary/vitals_fragment.php");
<?php } ?>

<?php
// Initialize for each applicable LBF form.
$gfres = sqlStatement("SELECT option_id FROM list_options WHERE " .
        "list_id = 'lbfnames' AND option_value > 0 ORDER BY seq, title");
while ($gfrow = sqlFetchArray($gfres)) {
    ?>
                    $("#<?php echo $gfrow['option_id']; ?>_ps_expand").load("../patient_file/summary/lbf_fragment.php?formname=<?php echo $gfrow['option_id']; ?>");
    <?php
}
?>

<?php if ($active_reminders) { ?>
                    // show the active reminder modal
                    $("#reminder_popup_link").fancybox({
                        'overlayOpacity': 0.0,
                        'showCloseButton': true,
                        'frameHeight': 500,
                        'frameWidth': 500,
                        'centerOnScroll': false
                    }).trigger('click');
<?php } ?>

                $("#accordion").jqueryAccordion({
                    interval: 300,
                    fadeContent: true,
                    open: false,
                    defaultOpenIndex: 1
                });




                $('.iframe').click(function(e) {
                    e.preventDefault();
                    parent.$.fancybox({
                        href: this.href,
                        /*maxWidth: 900,
                         minHeight: auto,*/
                        /*fitToView: false,*/
                        fitToView: false,
                        type: 'iframe',
                        iframe: {
                               preload: false // fixes issue with iframe and IE
                        },
                        helpers: {
                            overlay: {
                                opacity: 0.3,
                                css: {
                                    'background': 'rgba(255, 254, 254,0.85)'
                                }
                            } // overlay
                        }, // helpers
                        beforeShow: function() {

                            /* this.width  = parseInt(this.element.data('fancybox-width'));  
                             this.height = parseInt(this.element.data('fancybox-height'));*/
                            /*this.width = $('.fancybox-iframe').contents().find('html').width();
                             this.height = $('.fancybox-iframe').contents().find('html').height();*/
                        },
                        afterClose: function() {
                            goPid(<?php echo $pid; ?>);
                        }//afterClose
                    }); // fancybox
                }); // click

                $('.iframeDOCS').click(function(e) {
                    e.preventDefault();
                    parent.$.fancybox({
                        href: this.href,
                        maxWidth: 700,
                        maxHeight: 300,
                        fitToView: false,
                        type: 'iframe',
                        iframe: {
                               preload: false // fixes issue with iframe and IE
                        },
                        helpers: {
                            overlay: {
                                opacity: 0.3,
                                css: {
                                    'background': 'rgba(255, 254, 254,0.85)'
                                }
                            } // overlay
                        }, // helpers
                        afterClose: function() {   }//afterClose
                    }); // fancybox
                }); // click		

                $('#editar_paciente').click(function(e) {
                    e.preventDefault();
                    parent.$.fancybox({
                        href: this.href,
                        minWidth: 850,
                        maxHeight: 550,
                        openEffect: 'none',
                        closeEffect: 'none',
                        fitToView: false,
                        type: 'iframe',
                        iframe: {
                               preload: false // fixes issue with iframe and IE
                        },
                        helpers: {
                            overlay: {
                                opacity: 0.3,
                                css: {
                                    'background': 'rgba(255, 254, 254,0.85)'
                                }
                            } // overlay
                        }, // helpers
                        afterClose: function() {
                            goPid(<?php echo $pid; ?>);
                        }//afterClose
                    }); // fancybox
                }); // click

                $('#historial_enlace').click(function(e) {
                    e.preventDefault();
                    parent.$.fancybox({
                        href: this.href,
                        minWidth: 1200,
                        maxHeight: 750,
                        openEffect: 'none',
                        closeEffect: 'none',
                        autoSize: true,
                        type: 'iframe',
                        iframe: {
                               preload: false // fixes issue with iframe and IE
                        },
                        helpers: {
                            overlay: {
                                opacity: 0.3,
                                css: {
                                    'background': 'rgba(255, 254, 254,0.85)'
                                }
                            } // overlay
                        }, // helpers
                        afterClose: function() {
                            /*goPid(<?php echo $pid; ?>);*/
                        }//afterClose
                    }); // fancybox
                }); // click

                $('#consulta').bind("click" ,function(e) {
                    e.preventDefault();
                    //check_current_encounter();
                    //if ( $("#enc_val").val() === 'false' ){
                    parent.$.fancybox({
                        href: this.href,
                        maxWidth: 700,
                        maxHeight: 300,
                        fitToView: false,
                        openEffect: 'none',
                        closeEffect: 'none',
                        type: 'iframe',
                        iframe: {
                               preload: false // fixes issue with iframe and IE
                        },
                        helpers: {
                            overlay: {
                                opacity: 0.3,
                                css: {
                                    'background': 'rgba(255, 254, 254,0.85)'
                                }
                            } // overlay
                        } // helpers
                    }); // fancybox
                }); // click

                $('#consulta_close').on("click" ,function() {
                    if( !confirm("Si desea cerrar la consulta anterior seleccione OK. Si quiere cargar la consulta anterior seleccione Cancel.") ){ 
                    
                        //jQuery.noConflict( true );
                        $("#info").load("../patient_file/summary/demographics.php?set_pid=<?php echo $the_pid ?>", function() {
                            $("#column_left").load("../patient_file/encounter/forms.php?set_encounter=<?php echo $the_encounter; ?>");
                        });


                    } else {
                        //close_open_encounters()
                        $("#info").load("../patient_file/summary/demographics.php?set_pid=<?php echo $_SESSION['pid']; ?>&closed_old=1");
                    }
                }); // click



                $('#documentos').click(function(e) {
                    e.preventDefault();
                    parent.$.fancybox({
                        href: this.href,
                        maxWidth: 800,
                        minHeight: 500,
                        fitToView: false,
                        type: 'iframe',
                        iframe: {
                               preload: false // fixes issue with iframe and IE
                        },
                        helpers: {
                            overlay: {
                                opacity: 0.3,
                                css: {
                                    'background': 'rgba(255, 254, 254,0.85)'
                                }
                            } // overlay
                        }, // helpers
                        afterClose: function() {
                            //timeline
                            $("#column_left").load("../patient_file/summary/get_encounters.php", function() {
                                $("#by_doc").click();
                                $("#by_doc").addClass("active");
                            });

                        }//afterClose,
                    }); // fancybox
                }); // click

                $('#documentosEncounter').click(function(e) {
                    e.preventDefault();
                    parent.$.fancybox({
                        href: this.href,
                        maxWidth: 800,
                        minHeight: 500,
                        fitToView: false,
                        type: 'iframe',
                        iframe: {
                               preload: false // fixes issue with iframe and IE
                        },
                        helpers: {
                            overlay: {
                                opacity: 0.3,
                                css: {
                                    'background': 'rgba(255, 254, 254,0.85)'
                                }
                            } // overlay    
                        }, // helpers
                        afterClose: function() {        
                            //timeline
                            $("#column_left").load("../patient_file/encounter/forms.php?set_encounter=<?php echo $the_encounter; ?>", function() {
                                $("#documentos").css("display:none !important;");
                                $("#by_doc").click();
                                $("#by_doc").addClass("active");
                            });

                        }//afterClose,
                    }); // fancybox
                }); // click

                $('#portal_paciente').click(function(e) {
                    e.preventDefault();
                    parent.$.fancybox({
                        href: this.href,
                        maxWidth: 700,
                        minHeight: 300,
                        fitToView: false,
                        type: 'iframe',
                        iframe: {
                               preload: false // fixes issue with iframe and IE
                        },
                        helpers: {
                            overlay: {
                                opacity: 0.3,
                                css: {
                                    'background': 'rgba(255, 254, 254,0.85)'
                                }
                            } // overlay
                        }, // helpers
                        beforeShow: function() {
                            /*this.width = $('.fancybox-iframe').contents().find('html').width();
                             this.height = $('.fancybox-iframe').contents().find('html').height();*/
                        },
                    }); // fancybox
                }); // click

                $('#borrar_paciente').click(function(e) {
                    e.preventDefault();
                    parent.$.fancybox({
                        href: this.href,
                        maxWidth: 700,
                        maxHeight: 400,
                        fitToView: false,
                        type: 'iframe',
                        iframe: {
                               preload: false // fixes issue with iframe and IE
                        },
                        helpers: {
                            overlay: {
                                opacity: 0.3,
                                css: {
                                    'background': 'rgba(255, 254, 254,0.85)'
                                }
                            } // overlay
                        }, // helpers
                        beforeShow: function() {
                            /*this.width = $('.fancybox-iframe').contents().find('html').width();
                             this.height = $('.fancybox-iframe').contents().find('html').height();*/
                        },
                    }); // fancybox
                }); // click

                $('#loadPatient').click(function(e) {
                    e.preventDefault();
                    $("#info").load("../patient_file/summary/demographics.php?set_pid=" + pid);
                });
                
                /*$('#notepad').click(function(e) {
                    e.preventDefault();
                    var obj;
                    var result;
                    
                    obj = new ActiveXObject("Integrador.Integrador")

                    result =obj.Iniciar_Aplicacion("C:\\Program Files (x86)\\Notepad++\\notepad++.exe")
                });*/
        });
        </script>
    </head>
    <body class="body_top">
        <?php /* echo "<pre>";
          print_r($_SESSION);
          echo "</pre>"; */ ?>
        <div id="main">
            <a href='../reminder/active_reminder_popup.php' id='reminder_popup_link' style='visibility: false;' class='iframe'></a>

            <?php
            $thisauth = acl_check('patients', 'demo');
            if ($thisauth) {
                if ($result['squad'] && !acl_check('squads', $result['squad']))
                    $thisauth = 0;
            }

            if (!$thisauth) {
                echo "<p>(" . htmlspecialchars(xl('Demographics not authorized'), ENT_NOQUOTES) . ")</p>\n";
                echo "</body>\n</html>\n";
                exit();
            }
            ?>
            <!-- start main_toolbar -->
            <div id="main_toolbar">
                <p>	
                    <?php
                    if ($thisauth) {
                        echo "<span id='welcome'>Expediente: " . htmlspecialchars(getPatientName($pid), ENT_NOQUOTES) . "</span>";

                        if( acl_check('patients', 'ptntptns') ){ 
                        echo "<span id='buttons' style='float: right;'>";
						 }else{ 
							echo "<span style='float: right;display:none;'>";
						 } 

                        //Btn borrar paciente
                        if (acl_check('admin', 'root')) {
                            echo "<a id='borrar_paciente' class='css_button' style='font-size: 24px; padding: 5px 10px;' title='" . htmlspecialchars(xl('Delete'), ENT_NOQUOTES) . "' href='../patient_file/deleter.php?patient=" .
                            htmlspecialchars($pid, ENT_QUOTES) . "'>" .
                            "<i class='icon-remove'></i></a>";
                        }

                        if ($GLOBALS['erx_enable']) {
                            echo '<a class="css_button" href="../../eRx.php?page=medentry" onclick="top.restoreSession()">';
                            echo "<span>" . htmlspecialchars(xl('NewCrop MedEntry'), ENT_NOQUOTES) . "</span></a>";
                            echo '<a class="css_button iframe1" href="../../soap_functions/soap_accountStatusDetails.php" onclick="top.restoreSession()">';
                            echo "<span>" . htmlspecialchars(xl('NewCrop Account Status'), ENT_NOQUOTES) . "</span></a><td id='accountstatus'></td>";
                        }

                        //Btn Patient Portal
                        /*$portalUserSetting = true; //flag to see if patient has authorized access to portal
                        if ($GLOBALS['portal_onsite_enable'] && $GLOBALS['portal_onsite_address']) {
                            $portalStatus = sqlQuery("SELECT allow_patient_portal FROM patient_data WHERE pid=?", array($pid));
                            if ($portalStatus['allow_patient_portal'] == 'YES') {
                                $portalLogin = sqlQuery("SELECT pid FROM `patient_access_onsite` WHERE `pid`=?", array($pid));
                                echo "<a id='portal_paciente' class='css_button' style='font-size: 24px; padding: 5px 10px;' title='" . htmlspecialchars(xl('Reset Onsite Portal Credentials'), ENT_NOQUOTES) . "' href='../patient_file/summary/create_portallogin.php?portalsite=on&patient=" . htmlspecialchars($pid, ENT_QUOTES) . "'>";
                                echo "<i class='icon-globe'></i></a>";
                            } else {
                                $portalUserSetting = false;
                            }
                        }*/
                        //Btn Telemedicina
                        /* LINKS DE TELEMEDICINA */
            
                        /*echo "<pre>";
                        print_r($_SESSION);
                        echo "</pre>";*/
                        
                        if(!acl_check('admin', 'adm_cnf') ){
                            if(($_SESSION['pc_facility']>=19)&&($_SESSION['pc_facility']<=22)){
                                echo "<a id='telemedicina' class='css_button iframeDOCS' style='font-size: 24px; padding: 5px 10px;' title='Iniciar sesión de Telemedicina' href='" . $web_root . "/interface/forms/telemedicina/new.php'>";
                                echo "<i class='icon-desktop menu_icon_size'></i></a>";
                            }else{
                                echo '<a id="telemedicina2" class="css_button" style="font-size: 24px; padding: 5px 10px;" title="Iniciar sesión de Telemedicina" href="#" onclick="alert(\'Falta configurar la direccion IP de su equipo de Telemedicina.\nPor favor contacte al Administrador.\');">';
                                echo "<i class='icon-desktop menu_icon_size'></i></a>";
                            }
                            
                            //Btn Notepad
                            /*echo "<a id='notepad' class='css_button' style='font-size: 24px; padding: 5px 10px;' title='Iniciar Notepad' href='#'>";
                            echo "<i class='icon-heart menu_icon_size'></i></a>";*/

                            //Btn docs
                            echo "<a id='documentos' class='css_button' style='font-size: 24px; padding: 5px 10px;' title='" . htmlspecialchars(xl('Documents'), ENT_NOQUOTES) . "' href='" . $web_root . "/controller.php?document&list&patient_id=" . htmlspecialchars($pid, ENT_QUOTES) . "'>";
                            echo "<i class='icon-paper-clip menu_icon_size'></i></a>";

                            echo "<a id='documentosEncounter' class='css_button' style='font-size: 24px; padding: 5px 10px;display: none !important' title='" . htmlspecialchars(xl('Documents'), ENT_NOQUOTES) . "' href='" . $web_root . "/controller.php?document&list&patient_id=" . htmlspecialchars($pid, ENT_QUOTES) . "'>";
                            echo "<i class='icon-paper-clip menu_icon_size'></i></a>";                        
                        }
                        //Btn visita
                        $queryi = " SELECT *, form_encounter.date date2 
                                        FROM `form_encounter` inner join patient_data on ( form_encounter.pid = patient_data.pid )
                                        WHERE form_encounter.provider_id = " . $_SESSION['authUserID'] . " AND form_encounter.closed = 0 ";
                            $resulti = sqlStatement($queryi);
                            $rowi = sqlFetchArray($resulti);
                            $docdate = substr($rowi['date2'], 8, 2) . '/' . substr($rowi['date2'], 5, 2) . '/' . substr($rowi['date2'], 0, 4);
                        if(!acl_check('admin', 'adm_cnf') ){
                            if( check_open_encounter() ){
                                echo '<a id="consulta_close" title="Cerrar Consulta" class="css_button_consulta"><i class="icon-stethoscope"></i> Cerrar consulta<br><span>Paciente: '.$rowi['fname'].' '.$rowi['lname'].'</span><br><span>Fecha: '.$docdate.'</span></a>';                            
                                echo '<a style="display:none" href="../forms/newpatient/new.php?autoloaded=1&amp;calenc=" id="consulta" title="Crear Consulta1" class="css_button_consulta"><i class="icon-stethoscope"></i> Crear consulta</a>';
                            }else{
                                echo '<a id="consulta_close" style="display:none" title="Cerrar Consulta" class="css_button_consulta"><i class="icon-stethoscope"></i> Cerrar consulta<br><span>Paciente: '.$rowi['fname'].' '.$rowi['lname'].'</span><br><span>Fecha: '.$docdate.'</span></a>';
                                echo '<a href="../forms/newpatient/new.php?autoloaded=1&amp;calenc=" id="consulta" title="Crear Consulta1" class="css_button_consulta"><i class="icon-stethoscope"></i> Crear consulta</a>';
                            }
                        }
                        
                        


                        if (!($portalUserSetting)) {
                            // Show that the patient has not authorized portal access
                            //echo htmlspecialchars(xl('Patient has not authorized the Patient Portal.'), ENT_NOQUOTES);
                        }
                        //Patient Portal
                        // If patient is deceased, then show this (along with the number of days patient has been deceased for)
                        $days_deceased = is_patient_deceased($pid);
                        if ($days_deceased) {
                            echo "<td style='padding-left:1em;font-weight:bold;color:red'>" . htmlspecialchars(xl('DECEASED'), ENT_NOQUOTES) . " (" . htmlspecialchars($days_deceased, ENT_NOQUOTES) . " " . htmlspecialchars(xl('days ago'), ENT_NOQUOTES) . ")</td>";
                        }

                        echo "</span>";
                    }

                    // Get the document ID of the patient ID card if access to it is wanted here.
                    $idcard_doc_id = false;
                    if ($GLOBALS['patient_id_category_name']) {
                        $idcard_doc_id = get_document_by_catg($pid, $GLOBALS['patient_id_category_name']);
                    }
                    ?>
                </p>
            </div> 
            <!-- end main_toolbar -->

            <!-- start main content div -->
            <div style='margin-top:10px'> 
                <!-- start left column div -->
                <?php if (acl_check('patients', 'ptntdcmnts')) { ?>
                    <div id="column_left"></div>
                <?php } else { ?>
                    <div id="column_left" style='display:none;'></div>
<?php } ?>
                <!-- end left column div -->

                <?php
                $existeAutorizacionDatosGenerales = existeAutorizacionDatosGeneralesPaciente($_SESSION['authUserID'], $pid);
                ?>
                <!-- start right column div -->
                <div id="column_right">
                    <!-- Info demografica -->
                    <div id="patient" class="border">
                        <div id="patient_gnl">
                            <div style="float: left; margin-left: 4px; border: 1px solid rgb(228, 227, 227);">
                                <?php
                                $tmp = pic_array();
                                echo $tmp[0];
                                ?>
                            </div>
                            <div style="float: right;width: 120px;">
                                <p style="padding: 0px; font-size: 15px; margin-top: 0px; color: rgb(162, 162, 162);">
                                    <span style="color: rgb(67, 172, 164); font-size: 18px; font-weight: 700; line-height: 100%;"><?php echo htmlspecialchars($result['fname'] . " " . $result['lname'] . " " . $result['lname2'], ENT_NOQUOTES); ?></span><br/>
                                    <?php
                                    echo "<b style='font-size: 12px;'>";
                                    $date = new DateTime($result['DOB']);
                                    echo $date->format('d/m/Y') . "</b> <span style='font-size: 11px;'>(FEC NAC)</span><br/>";
                                    echo htmlspecialchars(getPatientAge($result['DOB_YMD']), ENT_QUOTES) . "  a&ntilde;os.<br/>";
                                    if ($result['country_code'] != '') {
                                        echo "<b style='font-size: 12px;'>" . $result['country_code'] . "</b> <span style='font-size: 11px;'>(PAIS)</span><br/>";
                                    }
                                    ?>
                                </p>
                            </div>
                        </div>

                        <?php
                        /* if ($existeAutorizacionDatosGenerales) { */
                        if (true) {
                            ?>
                            <div class="patient_info_left">
                                <a id="editar_paciente" title="Editar" href="<?php echo $web_root; ?>/patients/demographics_full.php?medico=1&set_pid=<?php echo $_REQUEST['set_pid']; ?>" class="css_button_small fancybox.iframe"><i class="icon-edit"></i></a>

                                <h2>SEXO:</h2> <p><?php
                                    if ($result['sex'] == "Female") {
                                        echo "Femenino";
                                    } else {
                                        echo "Masculino";
                                    }
                                    ?></p>
                                <?php
                                if ($result['email'] != '') {
                                    ?>
                                    <h2>EMAIL:</h2> <p><?php echo $result['email_patient']; ?></p>
                                    <?php
                                }
                                ?>

                            </div>
                            <div class="patient_info_left">
                                <h2>DIRECCION:</h2>
                                <p><?php echo $result['street']; ?></p>
                            </div>
                            <div class="patient_info_left">
                                <h2>TELEFONO:</h2>
                                <ul>
                                    <?php
                                    if ($result['phone_home'] != '') {
                                        echo "<li>" . $result['phone_home'] . " (# CASA)</li>";
                                    }

                                    if ($result['phone_cell'] != '') {
                                        echo "<li>" . $result['phone_cell'] . " (# CEL)</li>";
                                    }
                                    ?>
                                </ul>
                            </div>
                            <?php
                        }
                        ?>
                    </div>

                    <!-- Info Historia -->
                    <div id="column_historial" class="border">
                        <div class="historial_paciente">
                            <span>Historial Paciente <a title='Ver historial' href='<?php echo $web_root; ?>/patients/history_full.php?medico=1&pid=<?php echo $_REQUEST['set_pid']; ?>' class="css_button iframe_grafico btnNav fancybox.iframe" id='historial_enlace' style='padding: 3px 6px;font-size:15px;'><i class="icon-file-text-alt" style="font-size: 1.4em;"></i></a></span>
                        </div>
                    </div> 
                    <?php
                    if (acl_check('patients', 'crdn')) {
                        ?>
                        <div id="accordion" class="accordion" style="float: left; margin-bottom: 5px;">
                            <?php
                        } else {
                            ?>
                            <div id="accordion" class="accordion" style="float: left; margin-bottom: 5px;display:none">
                                <?php
                            }
                            ?>
                            <!-- Constantes Vitales -->
                            <div class="accordion-item">
                                <div class="accordion-header">
                                    <span class="title"><?php echo xl("Vitals"); ?></span>
                                    <i class="icon-bar-chart"></i>
                                </div>	
                                <div class="accordion-content">
                                    <div id="signos" class="patient_secondary"></div>	
                                </div>
                            </div>

                            <!--Odontograma>
                            <div class="accordion-item">
        <div class="accordion-header">
            <span class="title" id='odontograma'>Odontograma</span>
        </div>	
    </div>
                            <!--Odontograma-->


                            <!-- Citas -->
                            <div class="accordion-item">
                                <div class="accordion-header">
                                    <span class="title"><?php echo xl("Appointments"); ?></span>
                                    <i class="icon-calendar"></i>
                                </div>	
                                <div class="accordion-content">
                                    <div id="citas" class="patient_secondary"></div>	
                                </div>  
                            </div>



                            <!-- Recordatorios Clinicos -->
                            <div class="accordion-item">
                                <div class="accordion-header">
                                    <span class="title"><?php echo xl("Clinical Reminders"); ?></span>
                                    <i class="icon-time"></i>
                                </div>	
                                <div class="accordion-content">
                                    <?php
                                    if ((acl_check('patients', 'med')) && ($GLOBALS['enable_cdr'] && $GLOBALS['enable_cdr_crw'])) {
                                        echo '<div class="patient_secondary" id="' . xl("Clinical Reminders") . '">';
                                        $widgetButtonLink = "../patient_file/reminder/clinical_reminders.php?patient_id=" . $pid;
                                        echo "<h2>" . xl("Clinical Reminders");
                                        if(acl_check('admin', 'root') ){
                                            echo "<a class='addIcon css_button iframe css_button_left' title='" . htmlspecialchars(xl('Edit'), ENT_NOQUOTES) . "' href='" . $widgetButtonLink . "'>";
                                            echo '<i class="icon-plus-sign"></i>';
                                            echo "</a>";
                                        }
                                        echo "</h2>";

                                        echo '<div class="summary_item small patient_secondary" 7px;="" padding:="" id="clinical_reminders_ps_expand"></div>';
                                        echo "</div>";
                                    }
                                    ?>	
                                </div>
                            </div>


                            <!-- Problemas medicos, alergias, medicamentos-->
                            <?php
                            $numcols = '1';
                            $erx_upload_complete = 0;
                            $old_key = "";
                            $display_current_medications_below = 1;
                            foreach ($ISSUE_TYPES as $key => $arr) {
                                $query = "SELECT * FROM lists WHERE pid = ? AND type = ? AND ";
                                $query .= "(enddate is null or enddate = '' or enddate = '0000-00-00') ";
                                if ($GLOBALS['erx_enable'] && $GLOBALS['erx_medication_display'] && $key == 'medication')
                                    $query .= "and erx_uploaded != '1' ";
                                if ($GLOBALS['erx_enable'] && $GLOBALS['erx_allergy_display'] && $key == 'allergy')
                                    $query .= "and erx_uploaded != '1' ";
                                $query .= "ORDER BY begdate";
                                $pres = sqlStatement($query, array($pid, $key));

                                if (sqlNumRows($pres) > 0 || $arr[4] == 1) {
                                    $old_key = $key;
                                    if ($arr[0] == 'Diagnósticos Médicos') {
                                        echo '<div class="accordion-item">';
                                        echo '<div class="accordion-header"><span class="title">' . htmlspecialchars($arr[0], ENT_NOQUOTES) . '</span>';
                                        if ($key == "medical_problem") {
                                            echo '<i class="icon-user-md"></i>';
                                        } else if ($key == "allergy") {
                                            echo '<i class="icon-leaf"></i>';
                                        } else if ($key == "medication") {
                                            echo '<i class="icon-medkit"></i>';
                                        } else {
                                            echo '<i class="icon-info"></i>';
                                        }
                                        echo '</div>';
                                        echo '<div class="accordion-content">';

                                        if ($key == "medical_problem") {
                                            echo "<div id='problemasMedicos' class='patient_secondary'></div>";
                                        } else if ($key == "medication") {
                                            echo "<div id='medicamentos' class='patient_secondary'></div>";
                                        } else {
                                            echo "<div id='alergias' class='patient_secondary'></div>";
                                        }
                                        echo '</div>';
                                        echo '</div>';
                                    }
                                }
                            }
                            ?>			


                            <!-- Prescripciones -->
                            <div class="accordion-item">
                                <div class="accordion-header">
                                    <span class="title"><?php echo "Prescripciones"; //xl('Prescription History');                ?></span>
                                    <i class="icon-list-alt"></i>
                                </div>	
                                <div class="accordion-content">
                                        <?php if (!$GLOBALS['disable_prescriptions']) { ?>
                                        <div id="patient_stats_prescriptions" class='patient_secondary'>
                                            <?php
                                            // Issues expand collapse widget
                                            $widgetLabel = "prescriptions";
                                            if ($GLOBALS['erx_enable']) {
                                                $widgetTitle = xl('Prescription History');
                                                $widgetButtonLabel = xl("Add/Edit eRx");
                                                $widgetButtonLink = $GLOBALS['webroot'] . "/interface/eRx.php?page=compose";
                                            } else {
                                                $widgetTitle = xl('Prescription');
                                                $widgetButtonLabel = xl("Edit");
                                                $widgetButtonLink = $GLOBALS['webroot'] . "/interface/patient_file/summary/rx_frameset.php";
                                            }
                                            $widgetButtonLink = $GLOBALS['webroot'] . "/controller.php?prescription&edit&id=&pid=" . $pid;
                                            $rezz = sqlStatement("select * from prescriptions where patient_id=$pid and active='1' order by start_date DESC");
                                            //echo $widgetButtonLink;
                                            echo '<div class="patient_secondary" id="' . $widgetLabel . '">';
                                            echo "<h2>" . $widgetTitle . "<span style='float: right; background-color: rgb(228, 228, 228); border-radius: 5px 5px 5px 5px; border-right: 1px solid rgb(204, 204, 204); border-width: 2px 1px 1px; border-style: solid; border-color: -moz-use-text-color rgb(204, 204, 204) rgb(204, 204, 204); -moz-border-top-colors: none; -moz-border-right-colors: none; -moz-border-bottom-colors: none; -moz-border-left-colors: none; border-image: none; padding: 0px 10px;'> " . sqlNumRows($rezz) . " </span>";
                                            echo "<a class='addIcon css_button iframe css_button_left' title='" . $widgetButtonLabel . "' href='" . $widgetButtonLink . "'>";
                                            echo '<i class="icon-plus-sign"></i>';
                                            echo "</a></h2>";
                                            echo '<div id="prescriptions_ps_expand">';
                                            $res = sqlStatement("select * from prescriptions where patient_id=? and active='1'", array($pid));
                                            if (sqlNumRows($res) > 0) {
                                                echo "<table>";
                                                while ($row_currentMed = sqlFetchArray($res)) {
                                                    $runit = generate_display_field(array('data_type' => '1', 'list_id' => 'drug_units'), $row_currentMed['unit']);
                                                    $rin = generate_display_field(array('data_type' => '1', 'list_id' => 'drug_form'), $row_currentMed['form']);
                                                    $rroute = generate_display_field(array('data_type' => '1', 'list_id' => 'drug_route'), $row_currentMed['route']);
                                                    $rint = generate_display_field(array('data_type' => '1', 'list_id' => 'drug_interval'), $row_currentMed['interval']);
                                                    echo "<tr class=text ><td>" . $row_currentMed['drug'] . "</td><td>";
                                                    $unit = '';
                                                    if ($row_currentMed['size'] > 0)
                                                        $unit = $row_currentMed['size'] . " " . $runit . " "; echo htmlspecialchars($unit . " " . $row_currentMed['dosage'] . " " . $rin . " " . $rroute . " " . $rint, ENT_NOQUOTES);
                                                    ?>
                                                    <a id="borrar<?php echo $row_currentMed['id'] ?>" class="enlace_borrar iframe_grafico btnNav fancybox.iframe" title="Borrar" href="<?php echo $web_root; ?>/patients/deleter.php?prescription=<?php
                                                    echo $row_currentMed['id'];
                                                    echo "&medico=1&pid=$pid";
                                                    ?>">
                                                        <i class="icon-remove"></i>
                                                    </a>
                                                    <?php
                                                    echo "</td>";
                                                    echo "</tr>";
                                                }
                                                echo "</table>";
                                            }
                                            echo '</div>';
                                            echo "</div>";

//                                        /*
//                                          $cwd= getcwd();
//                                          chdir("../../../");
//                                          require_once("library/classes/Controller.class.php");
//                                          $c = new Controller();
//                                          echo $c->act(array("prescription" => "", "fragment" => "", "patient_id" => $pid));
//                                         */
                                            ?>
                                        </div>
<?php } ?>	
                                </div>
                            </div>

                            <!-- Problemas medicos, alergias, medicamentos-->
                            <?php
                            $numcols = '1';
                            $erx_upload_complete = 0;
                            $old_key = "";
                            $display_current_medications_below = 1;
                            foreach ($ISSUE_TYPES as $key => $arr) {
                                $query = "SELECT * FROM lists WHERE pid = ? AND type = ? AND ";
                                $query .= "(enddate is null or enddate = '' or enddate = '0000-00-00') ";
                                if ($GLOBALS['erx_enable'] && $GLOBALS['erx_medication_display'] && $key == 'medication')
                                    $query .= "and erx_uploaded != '1' ";
                                if ($GLOBALS['erx_enable'] && $GLOBALS['erx_allergy_display'] && $key == 'allergy')
                                    $query .= "and erx_uploaded != '1' ";
                                $query .= "ORDER BY begdate";
                                $pres = sqlStatement($query, array($pid, $key));

                                if (sqlNumRows($pres) > 0 || $arr[4] == 1) {
                                    $old_key = $key;
                                    if ($arr[0] != 'Diagnósticos Médicos') {
                                        echo '<div class="accordion-item">';
                                        echo '<div class="accordion-header"><span class="title">' . htmlspecialchars($arr[0], ENT_NOQUOTES) . '</span>';
                                        if ($key == "medical_problem") {
                                            echo '<i class="icon-user-md"></i>';
                                        } else if ($key == "allergy") {
                                            echo '<i class="icon-leaf"></i>';
                                        } else if ($key == "medication") {
                                            echo '<i class="icon-medkit"></i>';
                                        } else {
                                            echo '<i class="icon-info"></i>';
                                        }
                                        echo '</div>';
                                        echo '<div class="accordion-content">';

                                        if ($key == "medical_problem") {
                                            echo "<div id='problemasMedicos' class='patient_secondary'></div>";
                                        } else if ($key == "medication") {
                                            echo "<div id='medicamentos' class='patient_secondary'></div>";
                                        } else {
                                            echo "<div id='alergias' class='patient_secondary'></div>";
                                        }
                                        echo '</div>';
                                        echo '</div>';
                                    }
                                }
                            }
                            ?>			

                            <!-- end accordion-->
                        </div>
                        <!-- end right column div -->
                    </div> 
                    <!-- end main content div -->
                </div> 
                <!-- main -->
                <input type="hidden" id="enc_val" name="enc_val">
                </input>
                </body>
                </html>